_chessboard=(function(chessboard){
  var context, width, height, cell_width, radius, tagSize;
  
  chessboard.init = function(node, w) {
    var canvas = $('<canvas/>').attr('width', w).attr('height', w).appendTo(node);
    canvas.on('click', function(event){
      var x = Math.floor(event.offsetX / cell_width);
      var y = Math.floor(event.offsetY / cell_width);
      chessboard.onclick && chessboard.onclick(x, y);
    });
    
    context = canvas[0].getContext('2d');
    width = w;
    height = w;
    cell_width = w/8;
    radius = Math.max((cell_width-5)/2, 5);
    tagSize = Math.min(5, radius/2);
    
    draw_background();
  }
  
  chessboard.draw = function(board, tagPos, turn) {
    draw_background();
    draw_map(board, turn);
    if (tagPos) {
      draw_tag(tagPos.x, tagPos.y);
    }
  }

  var draw_tag = function(x, y) {
    context.strokeStyle='#FF0000';
    context.fillStyle='#FF0000';
    context.beginPath();
    context.arc(x*cell_width+cell_width/2,y*cell_width+cell_width/2,tagSize,0,2*Math.PI);
    context.stroke();
    context.fill();
  }
  
  var draw_background = function() {
    context.fillStyle='#D0D0D0';
    context.fillRect(0,0,width,height);
    context.strokeStyle='#000000';
    context.beginPath();
    for(var i=0;i<9;i++) {
      context.moveTo(i*cell_width,0);
      context.lineTo(i*cell_width,height);
      
      context.moveTo(0, i*cell_width);
      context.lineTo(width,i*cell_width);
    }
    context.stroke();
  }
  
  var draw_map = function(board, turn) {
    for(var x=0;x<8;x++) {
      for(var y=0;y<8;y++) {
        var ch = board.charAt(y*8+x);
        switch(ch) {
          case 'b':
            context.strokeStyle='#000000';
            context.fillStyle='#000000';
            context.beginPath();
            context.arc(x*cell_width+cell_width/2,y*cell_width+cell_width/2,radius,0,2*Math.PI);
            context.stroke();
            context.fill();
            break;
          case 'w':
            context.strokeStyle='#000000';
            context.fillStyle='#FFFFFF';
            context.beginPath();
            context.arc(x*cell_width+cell_width/2,y*cell_width+cell_width/2,radius,0,2*Math.PI);
            context.stroke();
            context.fill();
            break;
          case 'x':
            if (turn) {
              context.strokeStyle='#FFFFFF';
              context.beginPath();
              context.arc(x*cell_width+cell_width/2,y*cell_width+cell_width/2,radius,0,2*Math.PI);
              context.stroke();
            }
            break;
          default:
            break;
        }
      }
    }
  }

  return chessboard;
})(window._chessboard || {});